"""
用户视图
处理用户相关的API请求
"""

from rest_framework import status, generics, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import update_session_auth_hash
from django.db import transaction
from django.http import Http404
import os
from django.conf import settings

from .models import User, UserProfile, UserAddress
from .serializers import (
    UserRegistrationSerializer, UserLoginSerializer, UserDetailSerializer,
    UserUpdateSerializer, UserAddressSerializer, PasswordChangeSerializer,
    UserListSerializer, UserProfileSerializer
)
from utils.response import success_response, error_response


class UserRegistrationView(APIView):
    """
    用户注册视图
    """
    
    permission_classes = [permissions.AllowAny]
    
    def post(self, request):
        """用户注册"""
        serializer = UserRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    user = serializer.save()
                    
                    # 生成JWT Token
                    refresh = RefreshToken.for_user(user)
                    
                    return success_response(
                        data={
                            'user': UserDetailSerializer(user).data,
                            'tokens': {
                                'access': str(refresh.access_token),
                                'refresh': str(refresh),
                            }
                        },
                        message="注册成功"
                    )
            except Exception as e:
                return error_response(
                    message=f"注册失败: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            return error_response(
                message="注册失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserLoginView(APIView):
    """
    用户登录视图
    """
    
    permission_classes = [permissions.AllowAny]
    
    def post(self, request):
        """用户登录"""
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            
            # 生成JWT Token
            refresh = RefreshToken.for_user(user)
            
            return success_response(
                data={
                    'user': UserDetailSerializer(user).data,
                    'tokens': {
                        'access': str(refresh.access_token),
                        'refresh': str(refresh),
                    }
                },
                message="登录成功"
            )
        else:
            return error_response(
                message="登录失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserProfileView(APIView):
    """
    用户个人信息视图
    
    注意：
    - 头像上传请使用专用的头像上传API: /api/v1/users/avatar/upload/
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """获取用户信息"""
        serializer = UserDetailSerializer(request.user)
        return success_response(
            data=serializer.data,
            message="获取用户信息成功"
        )
        
    def put(self, request):
        """更新用户信息"""
        # 获取当前登录用户
        user = request.user
        
        # 记录请求数据以便调试
        print(f"收到用户信息更新请求，用户ID: {user.id}")
        print(f"请求数据: {request.data}")
        
        # 检查请求中是否包含avatar字段，如果有则提示使用专门的头像上传API
        if 'avatar' in request.data:
            return error_response(
                message="头像上传请使用专用API: /api/v1/users/avatar/upload/",
                status_code=status.HTTP_400_BAD_REQUEST
            )
        
        # 使用UserUpdateSerializer验证和处理数据
        serializer = UserUpdateSerializer(user, data=request.data, partial=True)
        
        if serializer.is_valid():
            try:
                # 保存更新后的用户信息
                serializer.save()
                
                # 返回成功响应，包含更新后的用户详情
                return success_response(
                    data=UserDetailSerializer(user).data,
                    message="用户信息更新成功"
                )
            except Exception as e:
                # 处理保存过程中的异常
                print(f"保存用户信息时出错: {str(e)}")
                return error_response(
                    message="更新失败: " + str(e),
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            # 处理验证错误
            print(f"用户信息验证失败: {serializer.errors}")
            
            # 使用字符串拼接来构建错误消息，避免使用f-string
            error_messages = []
            for field_name in serializer.errors:
                errors = serializer.errors[field_name]
                for error in errors:
                    error_messages.append(field_name + ": " + str(error))
            
            # 构建详细错误信息字典
            detailed_errors = {}
            for field, errors in serializer.errors.items():
                detailed_errors[field] = [str(error) for error in errors]
            
            # 返回错误响应
            return error_response(
                message="更新失败: " + ", ".join(error_messages),
                data=detailed_errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserProfileUpdateView(APIView):
    """
    用户详细信息更新视图
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """获取用户详细信息"""
        try:
            profile = request.user.profile
            serializer = UserProfileSerializer(profile)
            return success_response(
                data=serializer.data,
                message="获取用户详细信息成功"
            )
        except UserProfile.DoesNotExist:
            # 如果用户详细信息不存在，创建一个
            profile = UserProfile.objects.create(user=request.user)
            serializer = UserProfileSerializer(profile)
            return success_response(
                data=serializer.data,
                message="创建并获取用户详细信息成功"
            )
    
    def put(self, request):
        """更新用户详细信息"""
        try:
            # 获取当前登录用户的详细信息
            profile = request.user.profile
        except UserProfile.DoesNotExist:
            # 如果用户详细信息不存在，创建一个
            profile = UserProfile.objects.create(user=request.user)
        except Exception as e:
            return error_response(
                message=str(e),
                status_code=status.HTTP_400_BAD_REQUEST
            )
        
        # 使用正确的UserProfileSerializer来更新用户详细信息
        serializer = UserProfileSerializer(profile, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return success_response(
                data=serializer.data,
                message="更新用户详细信息成功"
            )
        else:
            return error_response(
                message="更新失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class PasswordChangeView(APIView):
    """
    密码修改视图
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        """修改密码"""
        serializer = PasswordChangeSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            user = request.user
            user.set_password(serializer.validated_data['new_password'])
            user.save()
            
            # 更新会话认证
            update_session_auth_hash(request, user)
            
            return success_response(
                message="密码修改成功"
            )
        else:
            return error_response(
                message="密码修改失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserAvatarUploadView(APIView):
    """
    用户头像上传视图
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        """上传用户头像"""
        # 检查是否有文件上传
        if 'avatar' not in request.FILES:
            return error_response(
                message="未选择头像文件",
                status_code=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            user = request.user
            
            # 删除旧头像（如果存在）
            if user.avatar and os.path.exists(os.path.join(settings.MEDIA_ROOT, str(user.avatar))):
                os.remove(os.path.join(settings.MEDIA_ROOT, str(user.avatar)))
            
            # 保存新头像
            user.avatar = request.FILES['avatar']
            user.save()
            
            # 获取头像URL
            avatar_url = request.build_absolute_uri(user.avatar.url) if user.avatar else ''
            
            return success_response(
                data={
                    'avatar': avatar_url
                },
                message="头像上传成功"
            )
        except Exception as e:
            return error_response(
                message=f"头像上传失败: {str(e)}",
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def logout_view(request):
    """
    用户登出视图
    """
    try:
        refresh_token = request.data.get('refresh')
        if refresh_token:
            token = RefreshToken(refresh_token)
            token.blacklist()
        return success_response(message="登出成功")
    except Exception as e:
        return error_response(
            message=f"登出失败: {str(e)}",
            status_code=status.HTTP_400_BAD_REQUEST
        )


@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def check_auth_view(request):
    """
    检查用户认证状态
    """
    if request.user.is_authenticated:
        return success_response(
            data={
                'is_authenticated': True,
                'user': UserDetailSerializer(request.user).data
            }
        )
    else:
        return success_response(data={'is_authenticated': False})


@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def users_me_view(request):
    """
    获取当前登录用户信息
    """
    if request.user.is_authenticated:
        return success_response(data=UserDetailSerializer(request.user).data)
    else:
        return error_response(
            message="未登录",
            status_code=status.HTTP_401_UNAUTHORIZED
        )


class UserListView(APIView):
    """
    用户列表视图（管理员使用）
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """获取用户列表"""
        if request.user.role != 'admin':
            return error_response(
                message="无权限访问",
                status_code=status.HTTP_403_FORBIDDEN
            )
        
        users = User.objects.all()
        serializer = UserListSerializer(users, many=True)
        return success_response(
            data=serializer.data,
            message="获取用户列表成功"
        )


class UserAddressViewSet(APIView):
    """
    用户地址管理视图集
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """获取用户地址列表"""
        addresses = UserAddress.objects.filter(user=request.user)
        serializer = UserAddressSerializer(addresses, many=True)
        return success_response(
            data=serializer.data,
            message="获取地址列表成功"
        )
    
    def post(self, request):
        """创建新地址"""
        serializer = UserAddressSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return success_response(
                data=serializer.data,
                message="创建地址成功"
            )
        else:
            return error_response(
                message="创建地址失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserAddressDetailView(APIView):
    """
    用户地址详情视图
    """
    
    permission_classes = [permissions.IsAuthenticated]
    
    def get_object(self, pk):
        try:
            return UserAddress.objects.get(pk=pk, user=self.request.user)
        except UserAddress.DoesNotExist:
            raise Http404
    
    def get(self, request, pk):
        """获取地址详情"""
        address = self.get_object(pk)
        serializer = UserAddressSerializer(address)
        return success_response(
            data=serializer.data,
            message="获取地址详情成功"
        )
    
    def put(self, request, pk):
        """更新地址"""
        address = self.get_object(pk)
        serializer = UserAddressSerializer(address, data=request.data, context={'request': request}, partial=True)
        if serializer.is_valid():
            serializer.save()
            return success_response(
                data=serializer.data,
                message="更新地址成功"
            )
        else:
            return error_response(
                message="更新失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )
    
    def delete(self, request, pk):
        """删除地址"""
        address = self.get_object(pk)
        address.delete()
        return success_response(message="删除地址成功")
